package com.derek.omshopping.ui.mine.register;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.derek.omshopping.R;
import com.derek.omshopping.base.BaseActivity;
import com.derek.omshopping.bean.mine.LoginDatabaseEntity;
import com.derek.omshopping.bean.mine.UserBean;
import com.derek.omshopping.ui.mine.login.LoginActivity;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

public class RegisterActivity extends BaseActivity {


    @BindView(R.id.barimg)
    ImageView barimg;
    @BindView(R.id.etPhoneNum)
    EditText etPhoneNum;//手机号
    @BindView(R.id.getSecurity)
    TextView getSecurity;//验证码
    @BindView(R.id.rela)
    RelativeLayout rela;
    @BindView(R.id.activity_exchange_password)
    EditText activityExchangePassword;//密码
    @BindView(R.id.activity_register_pwd)
    EditText activityRegisterPwd;
    @BindView(R.id.testSecurity)
    Button testSecurity;
    @BindView(R.id.activity_register)
    LinearLayout activityRegister;


    private String number;
    private ProgressDialog dialog;
    private String mPwd;
    @Override
    public int getLayoutId() {
        return R.layout.activity_register;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        SMSSDK.registerEventHandler(ev); //注册短信回调监听
        ButterKnife.bind(this);
 }
    /*
    * 短信验证的回调监听*/
    private  EventHandler ev = new EventHandler(){
        @Override
        public void afterEvent(int event, int result, Object data) {
            if (result == SMSSDK.RESULT_COMPLETE) { //回调完成
                // 提交验证码成功,如果验证成功会在data里返回数据。data数据类型为HashMap<number,code>
                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                    HashMap<String, Object> mData = (HashMap<String, Object>) data;
                    String country = (String) mData.get("country");//返回的国家编号
                    String phone = (String) mData.get("phone");//返回用户注册的手机号

                    if (phone.equals(number)) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showDailog("恭喜你！通过验证");
                                dialog.dismiss();
                                // 将注册成功的手机号和密码存入数据库
                                UserBean loginDao = new UserBean(RegisterActivity.this);
                                loginDao.add(new LoginDatabaseEntity(1,String.valueOf(number), mPwd ));
                                Intent intnet = new Intent(RegisterActivity.this, LoginActivity.class);
                                startActivity(intnet);
                            }
                        });
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showDailog("验证失败");
                                dialog.dismiss();
                            }
                        });
                    }

                } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {//获取验证码成功
                    Log.e("TAG", "获取验证码成功");
                } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {//返回支持发送验证码的国家列表

                }
            } else {
                ((Throwable) data).printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showDailog("验证码错误");
                        dialog.dismiss();
                    }
                });
            }
        }
    };


    private void showDailog(String text) {
        new AlertDialog.Builder(this)
                .setTitle(text)
                .setPositiveButton("确定", null)
                .show();
    }

    /**
     * 获取验证码
     *
     * @param v
     */
    public void getSecurity(View v) {
        number = etPhoneNum.getText().toString().trim();

        //发送短信，传入国家号和电话---使用SMSSDK核心类之前一定要在MyApplication中初始化，否侧不能使用
        if (TextUtils.isEmpty(number)) {
            Toast.makeText(this, "号码不能为空！", Toast.LENGTH_SHORT).show();
        } else {
            // 判断数据库中是否已经存在该用户, 如果存在则不作任何操作, 否则进行注册
            UserBean login = new UserBean(this);
            List<LoginDatabaseEntity> allBean = login.getAllBean();
            int flag = 0;
            for (LoginDatabaseEntity entity : allBean){
                if (String.valueOf(number).equals(entity.getUsername())){
                    flag = 1;
                    break;
                }
            }
            if (flag == 1){
                Toast.makeText(RegisterActivity.this, "该用户已注册", Toast.LENGTH_SHORT).show();
            }else {
                // 发送短信验证码
                SMSSDK.getVerificationCode("+86", number);
                Toast.makeText(this, "发送成功:" + number, Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 向服务器提交验证码，在监听回调中判断是否通过验证
     *
     * @param v
     */
    public void testSecurity(View v) {
        String security = activityExchangePassword.getText().toString();
        mPwd = activityRegisterPwd.getText().toString();
        if (TextUtils.isEmpty(mPwd)){
            Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!TextUtils.isEmpty(security)) {
            dialog = ProgressDialog.show(this, null, "正在验证...", false, true);
            //提交短信验证码
            SMSSDK.submitVerificationCode("+86", number, security);//国家号，手机号码，验证码
            Toast.makeText(this, "提交了注册信息:" + number, Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "验证码不能为空", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 解除注册
        SMSSDK.unregisterAllEventHandler();
    }
}
